using aichat.Data;
using aichat.Entities;
using Microsoft.EntityFrameworkCore;

namespace aichat.Services
{
    public class PaymentService : IPaymentService
    {
        private readonly ApplicationDbContext _context;
        private readonly IUserService _userService;

        public PaymentService(ApplicationDbContext context, IUserService userService)
        {
            _context = context;
            _userService = userService;
        }

        public async Task<PaymentRecord> CreatePaymentAsync(int userId, VipType vipType, string paymentMethod)
        {
            var amount = await GetVipPriceAsync(vipType);
            var orderId = GenerateOrderId();

            var payment = new PaymentRecord
            {
                UserId = userId,
                OrderId = orderId,
                PaymentMethod = paymentMethod,
                Amount = amount,
                VipType = vipType,
                Status = PaymentStatus.Pending,
                Description = $"VIP会员购买 - {GetVipTypeName(vipType)}"
            };

            _context.PaymentRecords.Add(payment);
            await _context.SaveChangesAsync();

            return payment;
        }

        public async Task<bool> ProcessPaymentAsync(string orderId, string transactionId)
        {
            var payment = await _context.PaymentRecords
                .FirstOrDefaultAsync(p => p.OrderId == orderId);

            if (payment == null) return false;

            payment.Status = PaymentStatus.Paid;
            payment.TransactionId = transactionId;
            payment.PaidAt = DateTime.Now;

            // 更新用户VIP状态
            var expireDate = CalculateVipExpireDate(payment.VipType);
            await _userService.UpdateVipStatusAsync(payment.UserId, payment.VipType, expireDate);

            await _context.SaveChangesAsync();
            return true;
        }

        public async Task<PaymentRecord?> GetPaymentByOrderIdAsync(string orderId)
        {
            return await _context.PaymentRecords
                .FirstOrDefaultAsync(p => p.OrderId == orderId);
        }

        public async Task<List<PaymentRecord>> GetUserPaymentsAsync(int userId)
        {
            return await _context.PaymentRecords
                .Where(p => p.UserId == userId)
                .OrderByDescending(p => p.CreatedAt)
                .ToListAsync();
        }

        public async Task<decimal> GetVipPriceAsync(VipType vipType)
        {
            return vipType switch
            {
                VipType.Monthly => 29.99m,
                VipType.Yearly => 299.99m,
                VipType.Permanent => 999.99m,
                _ => 0m
            };
        }

        public async Task<string> GenerateAlipayUrlAsync(PaymentRecord payment)
        {
            // 这里应该集成真实的支付宝SDK
            // 目前返回模拟的支付URL
            return $"https://alipay.com/pay?orderId={payment.OrderId}&amount={payment.Amount}";
        }

        private string GenerateOrderId()
        {
            return $"ORDER{DateTime.Now:yyyyMMddHHmmss}{Random.Shared.Next(1000, 9999)}";
        }

        private string GetVipTypeName(VipType vipType)
        {
            return vipType switch
            {
                VipType.Monthly => "月度会员",
                VipType.Yearly => "年度会员",
                VipType.Permanent => "永久会员",
                _ => "未知"
            };
        }

        private DateTime? CalculateVipExpireDate(VipType vipType)
        {
            return vipType switch
            {
                VipType.Monthly => DateTime.Now.AddMonths(1),
                VipType.Yearly => DateTime.Now.AddYears(1),
                VipType.Permanent => null, // 永久会员无过期时间
                _ => null
            };
        }
    }
} 